package runner;

import com.alibaba.fastjson.JSON;
import drivers.PointEventCommandDriver;
import drivers.PointMDCommandDriver;
import net.protocol.carfun.CarFunProtocol;
import net.protocol.carfun.commands.Command;
import net.protocol.carfun.commands.MDCommand;
import net.socket.driver.providers.CommandDriverManager;
import net.socket.driver.providers.EventCommandDriverProvider;
import net.socket.driver.providers.MDCommandDriverProvider;
import net.socket.utils.Refection;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.List;

/**
 * @Author: Qiao Hang
 * @CreateDate: 2021/3/23 下午4:13
 * @UpdateDate:
 * @Description:
 */
public class ClientB {

    /**
     * 1.客户端输入bye会断联，发送结束socket请求
     *
     * 2.发送@+command
     * 3.发送data
     * 4.发送""
     *
     * 其中2,3,4 会解析一个客户端请求进行发送.
     */

    public static final String clientName = "Client-2";
    private static final Charset UTF_8 = Charset.forName("UTF-8");

    public static void main(String[] args) throws IOException {
        List<MDCommandDriverProvider> mdCommandDriverProviders =
                (List<MDCommandDriverProvider>) Refection.fieldGet(CommandDriverManager.class, "mdCommandDriverProviders", null);
        List<EventCommandDriverProvider> eventCommandDriverProviders =
                (List<EventCommandDriverProvider>) Refection.fieldGet(CommandDriverManager.class, "eventCommandDriverProviders", null);

        mdCommandDriverProviders.add(new MDCommandDriverProvider(){{
            add(new PointMDCommandDriver());
        }});

        eventCommandDriverProviders.add(new EventCommandDriverProvider(){{
            add(new PointEventCommandDriver());
        }});

        Socket socket = null;
        BufferedReader reader = null;
        PrintWriter writer = null;
        BufferedReader consoleReader = null;
        ServerReporter reporter = null;
        try {
            socket = new Socket("localhost",4477);
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), Charset.forName("UTF-8")));
            writer = new PrintWriter(socket.getOutputStream(),true);
            consoleReader = new BufferedReader(new InputStreamReader(System.in));
            //服务端响应收集reporter.
            reporter = new ServerReporter(reader,clientName);
            new Thread(reporter).start();

            String line = null;
            String commandStr = null;
            StringBuffer dataBuffer = new StringBuffer();
            Boolean dataNotAccepted = Boolean.TRUE;
            while (true){
                line = consoleReader.readLine();
                if(line.equalsIgnoreCase("bye")){
                    String endProtocol = CarFunProtocol.builder(MDCommand.Client.CLIENT_CONNECT_END)
                            .charSet(UTF_8)
                            .build().toString();
                    writer.write(endProtocol);
                    writer.flush();
                    break;
                }else if(line.startsWith("@")){
                    commandStr = line.substring(1);
                }else if(!line.equals("")){
                    dataBuffer.append(line);
                }else {
                    if(dataBuffer.length() == 0 && dataNotAccepted){
                        dataNotAccepted = Boolean.FALSE;
                        continue;
                    }
                    //构造协议发送请求.
                    Command command = null;
                    if(commandStr != null){
                        command = CommandDriverManager.parseMDCommand(commandStr);
                    }
                    if(command != null){
                        CarFunProtocol protocol = CarFunProtocol.builder(command).charSet(UTF_8);
                        String data = null;
                        if(dataBuffer.length() > 0){
                            String json = dataBuffer.toString();
                            if(JSON.isValid(json) || JSON.isValidArray(json)){
                                data = json;
                                if(!JSON.isValidObject(json)){
                                    protocol.isJSONAry(true);
                                }
                            }else {
                                // 既不是json，也不是jsonAry，也不是bye, 忽略.
                                protocol = null;
                            }
                        }
                        if(protocol != null){
                            StringBuffer build = protocol.data(data, UTF_8)
                                    .build();
                            writer.write(build.toString());
                            writer.flush();
                        }
                    }
                    commandStr = null;
                    dataBuffer = new StringBuffer();
                    dataNotAccepted = Boolean.TRUE;
                }
            }

        }catch (Throwable e){
            e.printStackTrace();
        }finally {
            if(reader != null){
                if(reporter != null){
                    reporter.setReader(null);
                }
                reader.close();
            }
            if(writer != null){
                writer.close();
            }
            if(consoleReader != null){
                consoleReader.close();
            }
            if(socket != null){
                socket.close();
            }
        }
    }
}
